package service

import (
	"context"
	"dache-server/basic/inits"
	__ "dache-server/basic/proto"
	"dache-server/handler/models"
	"dache-server/pkg"
	"dache-server/untils"
	"encoding/json"
	"errors"
	"fmt"
	"log"
	"math/rand"
	"strconv"
	"time"
)

// server is used to implement helloworld.GreeterServer.
type Server struct {
	__.UnimplementedDacheServer
}

// SayHello implements helloworld.GreeterServer
func (s *Server) SendSms(_ context.Context, in *__.SendSmsReq) (*__.SendSmsResp, error) {
	aLiYun := untils.AliYun{}
	intn := rand.Intn(9000) + 1000
	count, _ := inits.RedisDB.Get(inits.Ctx, "sendSmsCount:"+in.Mobile).Int()
	if count == 3 {
		return nil, fmt.Errorf("短信验证码一分钟内只能发送三次")
	}
	err := aLiYun.SendSms(in.Mobile, strconv.Itoa(intn))
	if err != nil {
		return nil, err
	}
	inits.RedisDB.Set(inits.Ctx, "SendSms:"+in.Mobile, intn, time.Minute*15)
	inits.RedisDB.Incr(inits.Ctx, "sendSmsCount:"+in.Mobile)
	inits.RedisDB.Expire(inits.Ctx, "sendSmsCount:"+in.Mobile, time.Minute*1)

	return &__.SendSmsResp{}, nil
}

// 用户注册
func (s *Server) Register(_ context.Context, in *__.RegisterReq) (*__.RegisterResp, error) {
	var user models.User
	user.Mobile = in.Mobile
	if err := user.GetUserByMobile(); err != nil {
		return nil, err
	}
	if user.Id > 0 {
		return nil, fmt.Errorf("用户已存在,请前往登录")
	}
	user.Username = in.Username
	user.Password = pkg.Md5(in.Password)
	user.Nickname = in.Nickname
	user.UserType = 3
	get := inits.RedisDB.Get(inits.Ctx, "SendSms:"+in.Mobile).Val()
	if get != in.SmsCode {
		return nil, fmt.Errorf("验证码错误")
	}
	if err := user.Register(); err != nil {
		return nil, fmt.Errorf("用户注册失败")
	}
	return &__.RegisterResp{
		UserId: int64(user.Id),
	}, nil
}

// 用户登录
func (s *Server) Login(_ context.Context, in *__.LoginReq) (*__.LoginResp, error) {
	var user models.User
	user.Mobile = in.Mobile
	if err := user.GetUserByMobile(); err != nil {
		return nil, err
	}
	if user.Id == 0 {
		return nil, fmt.Errorf("用户不存在存在,请前往注册")
	}

	if user.Password != pkg.Md5(in.Password) {
		return nil, fmt.Errorf("密码错误,请重新输入")
	}

	get := inits.RedisDB.Get(inits.Ctx, "SendSms:"+in.Mobile).Val()
	if get != in.SmsCode {
		return nil, fmt.Errorf("验证码错误")
	}

	return &__.LoginResp{
		UserId: int64(user.Id),
	}, nil
}

// 司机注册
func (s *Server) DriverRegister(_ context.Context, in *__.DriverRegisterReq) (*__.DriverRegisterResp, error) {
	var user models.User
	user.Id = uint(in.UserId)

	if err := user.GetUserById(int(in.UserId)); err != nil {
		return nil, err
	}
	if user.Id == 0 {
		return nil, fmt.Errorf("用户不存在")
	}
	user.UserType = 2
	if err := user.UpdateUser(); err != nil {
		return nil, err
	}
	driver := models.Driver{
		UserId:        uint(in.UserId),
		Drivername:    in.DriverName,
		DriverLicense: in.DriverLicense,
		DriverImg:     in.DriverImg,
		DrivingImg:    in.DrivingImg,
		Idcard:        in.Idcard,
		DriverStatus:  uint(in.DriverStatus),
	}
	if err := driver.RegisterDriver(); err != nil {
		return nil, fmt.Errorf("司机注册失败")
	}

	return &__.DriverRegisterResp{
		DriverId: int64(driver.Id),
	}, nil
}

// 修改司机信息
func (s *Server) UpdateDriverInfo(_ context.Context, in *__.UpdateDriverInfoReq) (*__.UpdateDriverInfoResp, error) {

	driver := models.Driver{
		Id:           uint(in.Id),
		DriverImg:    in.DriverImg,
		DrivingImg:   in.DrivingImg,
		DriverStatus: uint(in.DriverStatus),
	}
	if err := driver.UpdateDriver(); err != nil {
		return nil, fmt.Errorf("认证信息提交失败")
	}
	return &__.UpdateDriverInfoResp{
		Id: int64(driver.Id),
	}, nil
}

// 管理员审核司机信息
func (s *Server) AdminCheck(_ context.Context, in *__.AdminCheckReq) (*__.AdminCheckResp, error) {
	var user models.User
	user.Id = uint(in.UserId)
	if err := user.GetUserById(int(in.UserId)); err != nil {
		return nil, err
	}
	if user.Id == 0 {
		return nil, fmt.Errorf("用户不存在")
	}
	if user.UserType != 3 {
		return nil, fmt.Errorf("无权限审核司机认证")
	}
	driver := models.Driver{
		Id:           uint(in.DriverId),
		DriverStatus: uint(in.DriverStatus),
	}
	if err := driver.UpdateDriver(); err != nil {
		return nil, fmt.Errorf("审核司机认证信息失败")
	}
	return &__.AdminCheckResp{
		DriverId: int64(driver.Id),
	}, nil
}

// 车辆添加
func (s *Server) CarAdd(_ context.Context, in *__.CarAddReq) (*__.CarAddResp, error) {
	var user models.User
	user.Id = uint(in.UserId)
	if err := user.GetUserById(int(in.UserId)); err != nil {
		return nil, err
	}
	if user.Id == 0 {
		return nil, fmt.Errorf("用户不存在")
	}

	if user.UserType != 2 {
		return nil, fmt.Errorf("无权限添加车辆")
	}
	car := models.Car{
		UserId:        uint(in.UserId),
		CarColor:      in.CarColor,
		CarType:       in.CarType,
		CarBrand:      in.CarBrand,
		DrivingNumber: in.DrivingNumber,
		CarNumber:     in.CarNumber,
		SeatNum:       uint(in.SeatNum),
		CarImg:        in.CarImg,
		CarStatus:     uint(in.CarStatus),
	}
	if err := car.AddCar(); err != nil {
		return nil, fmt.Errorf("车辆添加失败")
	}
	return &__.CarAddResp{
		CarId: int64(car.Id),
	}, nil
}

// 车型列表展示
func (s *Server) GetCarList(_ context.Context, in *__.GetCarListReq) (*__.GetCarListResp, error) {
	var carLists []*__.CarList
	var c models.Car
	c.CarType = in.CarType
	list, err := c.GetCarList()
	get := inits.RedisDB.Get(inits.Ctx, "carList").Val()
	if get == "" {
		if err != nil {
			return nil, fmt.Errorf("车型列表展示失败")
		}
		for _, car := range list {
			carLists = append(carLists, &__.CarList{
				CarColor:  car.CarColor,
				CarType:   car.CarType,
				CarBrand:  car.CarBrand,
				CarNumber: car.CarNumber,
				SeatNum:   int64(car.SeatNum),
				CarImg:    car.CarImg,
				CarStatus: int64(car.CarStatus),
				Money:     float32(untils.TotalPrice(in.CarType)),
			})
		}
		marshal, _ := json.Marshal(carLists)

		inits.RedisDB.Set(inits.Ctx, string(marshal), "carList", time.Minute*60)
	} else {
		_ = json.Unmarshal([]byte(get), &__.CarList{})

	}

	return &__.GetCarListResp{
		List: carLists,
	}, nil
}

// 创建订单
func (s *Server) CreateOrder(_ context.Context, in *__.CreateOrderReq) (*__.CreateOrderResp, error) {
	//随机获取一个司机
	var driver models.Driver
	count, _ := driver.GetDriverWorkStatus()
	if len(count) == 0 {
		return nil, errors.New("没有司机接单")
	}
	index := rand.Intn(len(count))
	log.Println("1111", count)
	order := models.Order{
		OrderSn:     in.OrderSn,
		PassagerId:  uint(in.PassagerId),
		DriverId:    uint(count[index]),
		BeginTime:   time.Now(),
		OrderStatus: uint(in.OrderStatus),
		PayType:     uint(in.PayType),
		PayStatus:   uint(in.PayStatus),
		PayPrice:    untils.TotalPrice(in.CarType),
		Kilo:        float64(in.Kilo),
	}
	if err := order.CreateOrder(); err != nil {
		return nil, fmt.Errorf("订单创建失败")
	}
	driver = models.Driver{
		Id:         uint(count[index]),
		WorkStatus: 2,
	}
	if err := driver.UpdateDriver(); err != nil {
		return nil, err
	}
	untils.SyncEsToData()
	return &__.CreateOrderResp{
		OrderId: int64(order.Id),
	}, nil
}

// 司机修改接单状态
func (s *Server) DriverUpdateOrder(_ context.Context, in *__.DriverUpdateOrderReq) (*__.DriverUpdateOrderResp, error) {
	var order models.Order
	order.Id = uint(in.OrderId)
	order.OrderStatus = 1
	order.OrderMode = in.OrderMode
	if err := order.UpdateOrder(); err != nil {
		return nil, fmt.Errorf("订单修改失败")
	}
	return &__.DriverUpdateOrderResp{
		OrderId: int64(order.Id),
		Message: "订单结束",
	}, nil
}

// 司机拒单
func (s *Server) UpdateOrder(_ context.Context, in *__.UpdateOrderReq) (*__.UpdateOrderResp, error) {

	/*	var user models.User
		if err := user.GetUserById(int(in.DriverId)); err != nil {
			return nil, err
		}
		if user.UserType != 2 {
			return nil, errors.New("无权限修改订单")
		}*/
	order := models.Order{
		Id:          uint(in.OrderId),
		OrderStatus: 1,
	}
	if err := order.UpdateOrder(); err != nil {
		return nil, fmt.Errorf("订单状态修改失败")
	}

	return &__.UpdateOrderResp{
		OrderId: int64(order.Id),
	}, nil
}

// 核对用户手机号后四位
func (s *Server) GetUserMobileInfo(_ context.Context, in *__.GetUserMobileInfoReq) (*__.GetUserMobileInfoResp, error) {
	var order models.Order
	order.Id = uint(in.OrderId)
	if err := order.GetOrderById(); err != nil {
		return nil, err
	}
	if order.Id == 0 {
		return nil, fmt.Errorf("该订单不存在")
	}
	var user models.User

	if err := user.GetUserById(int(order.PassagerId)); err != nil {
		return nil, fmt.Errorf("获取用户信息失败")
	}

	if user.Mobile[7:11] != in.Mobile {
		return nil, fmt.Errorf("乘客手机号后四位错误")
	}
	order.OrderStatus = 3
	if err := order.UpdateOrder(); err != nil {
		return nil, fmt.Errorf("订单状态修改失败")
	}
	return &__.GetUserMobileInfoResp{
		Mobile:  user.Mobile,
		Message: "乘客手机号核实成功",
	}, nil
}

// 乘客支付
func (s *Server) PassagePay(_ context.Context, in *__.PassagePayReq) (*__.PassagePayResp, error) {
	var order models.Order
	order.Id = uint(in.OrderId)
	if err := order.GetOrderById(); err != nil {
		return nil, err
	}
	if order.Id == 0 {
		return nil, fmt.Errorf("该订单不存在")
	}
	if order.PassagerId != uint(in.UserId) {
		return nil, fmt.Errorf("该订单不是您的")
	}
	if order.PayStatus == 2 {
		return nil, fmt.Errorf("该订单已支付")
	}
	alipay := untils.Ali{}
	money := fmt.Sprintf("%.2f", order.PayPrice)

	return &__.PassagePayResp{
		PayUrl: alipay.Alipay(order.OrderSn, money),
	}, nil
}

// 修改订单为已支付
func (s *Server) UpdatePayOrder(_ context.Context, in *__.UpdatePayOrderReq) (*__.UpdatePayOrderResp, error) {
	var order models.Order
	order.Id = uint(in.OrderId)
	if err := order.GetOrderById(); err != nil {
		return nil, err
	}
	if order.Id == 0 {
		return nil, fmt.Errorf("该订单不存在")
	}
	order.PayStatus = 2
	if err := order.UpdateOrder(); err != nil {
		return nil, fmt.Errorf("订单状态修改失败")
	}
	return &__.UpdatePayOrderResp{
		OrderId: int64(order.Id),
		Message: "更新订单状态为“已支付”",
	}, nil
}

// 我的订单
func (s *Server) GetMyOrder(_ context.Context, in *__.GetMyOrderReq) (*__.GetMyOrderResp, error) {

	var orderLists []*__.OrderList
	var o models.Order
	o.OrderStatus = uint(in.OrderStatus)
	list, err := o.GetOrderList()
	if err != nil {
		return nil, fmt.Errorf("查询用户的历史订单失败")
	}
	for _, order := range list {
		orderLists = append(orderLists, &__.OrderList{
			OrderSn:     order.OrderSn,
			PassagerId:  int64(order.PassagerId),
			DriverId:    int64(order.DriverId),
			OrderStatus: int64(order.OrderStatus),
			PayType:     int64(order.PayType),
			PayStatus:   int64(order.PayStatus),
			PayPrice:    float32(order.PayPrice),
			Kilo:        float32(order.Kilo),
		})
	}
	//order := untils.SearchEs(int(in.PassagerId))
	return &__.GetMyOrderResp{
		List: orderLists,
	}, nil
}

// 获取订单详情
func (s *Server) GetOrderDetail(_ context.Context, in *__.GetOrderDetailReq) (*__.GetOrderDetailResp, error) {
	var order models.Order
	order.Id = uint(in.Id)
	if err := order.GetOrderDetail(); err != nil {
		return nil, fmt.Errorf("订单详情获取失败")
	}
	return &__.GetOrderDetailResp{
		Id:           int64(order.Id),
		OrderSn:      order.OrderSn,
		PassagerId:   int64(order.PassagerId),
		DriverId:     int64(order.DriverId),
		OrderStatus:  int64(order.OrderStatus),
		PayType:      int64(order.PayType),
		PayStatus:    int64(order.PayStatus),
		PayPrice:     float32(order.PayPrice),
		Kilo:         float32(order.Kilo),
		StartAddress: order.StartAddress,
		EndAddress:   order.EndAddress,
	}, nil
}
